﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace Jquery.DAL
{
    public class BaseRepository<T>  where T : class ,new()
    {
        DBjquery db = DbContextFactory.GetCurrentThreadDbContext();
        public IQueryable<T> LoadEntities(Func<T, bool> WhereLambda)
        {
            return db.Set<T>().Where<T>(WhereLambda).AsQueryable();
        }
        public IQueryable<T> LoadPageEntities<s>(int PageSize, int PageIndex, out int total, Func<T, bool> WhereLambda, Func<T, s> OrderLambda, bool IsAsc)
        {
            var data = db.Set<T>().Where<T>(WhereLambda);
            total = data.Count();

            if (IsAsc)
            {
                data = data.OrderBy<T, s>(OrderLambda).Skip<T>((PageSize - 1) * PageIndex).Take<T>(PageSize);
            }
            else
            {
                data = data.OrderByDescending<T, s>(OrderLambda).Skip<T>((PageSize - 1) * PageIndex).Take<T>(PageSize);
            }
            return data.AsQueryable();
        }

        public T Add(T t)
        {
            db.Set<T>().Add(t);
            db.SaveChanges();
            return t;
        }

        public bool update(T t)
        {
            db.Set<T>().Attach(t);
            db.Entry(t).State = EntityState.Modified;
            return db.SaveChanges() > 0;
        }

        public bool delete(T t)
        {
            db.Set<T>().Attach(t);
            db.Entry(t).State = EntityState.Deleted;
            return db.SaveChanges() > 0;
        }
    }
}
